<?php
/**
 * DBShop 电子商务系统
 *
 * ==========================================================================
 * @link      https://www.dbshop.net/
 * @copyright 北京珑大钜商科技有限公司，并保留所有权利。
 * @license   https://www.dbshop.net/license.html License
 * ==========================================================================
 *
 * @author    静静的风 <baron@loongdom.cn>
 *
 */

namespace User\Service;

use Doctrine\ORM\EntityManager;
use Goods\Entity\GoodsInSpecGoods;
use User\Entity\Cart;

class CartManager
{
    private $entityManager;

    public function __construct(
        EntityManager $entityManager
    )
    {
        $this->entityManager = $entityManager;
    }

    /**
     * 删除购物车里的指定商品
     * @param $goodsId
     * @return bool
     */
    public function deleteCartGoods($goodsId)
    {
        $qb = $this->entityManager->createQueryBuilder();
        $qb->delete(Cart::class, 'c')->where('c.goodsId = :goodsId')->setParameter('goodsId', $goodsId);
        $qb->getQuery()->execute();

        return true;
    }

    /*==============================================下面为前台调用==============================================*/
    /**
     * 添加购物车
     * @param array $data
     * @return object|Cart
     * @throws \Doctrine\ORM\ORMException
     * @throws \Doctrine\ORM\OptimisticLockException
     */
    public function addCart(array $data)
    {
        if(!empty($data['specTagIdStr'])) {
            $specTagIdArray = array_filter(explode(',', $data['specTagIdStr']), function ($value) { return (int) $value; });
            sort($specTagIdArray);
            $specGoods      = $this->entityManager->getRepository(GoodsInSpecGoods::class)->findOneBy(['tagIdStr' => implode('', $specTagIdArray), 'goodsId' => $data['goodsId']]);
            $inSpecGoodsId  = $specGoods->getInSpecGoodsId();
        } else $inSpecGoodsId = 0;

        //检查是否购物车中已经存在，如已经存在则进行更新处理
        $cartGoods = $this->entityManager->getRepository(Cart::class)->findOneBy(['inSpecGoodsId' => $inSpecGoodsId, 'goodsId' => $data['goodsId'], 'userId' => $data['userId'], 'buyNow' => $data['buyNow']]);
        if($cartGoods) {
            $data['buyNum'] = $cartGoods->getBuyNum() + $data['buyNum'];
            $cartGoods->valuesSet($data);
            $this->entityManager->flush();
            return $cartGoods;
        }

        $cart = new Cart();
        $cart->valuesSet($data);
        $cart->setInSpecGoodsId($inSpecGoodsId);
        $cart->setAddTime(time());

        $this->entityManager->persist($cart);
        $this->entityManager->flush();

        return $cart;
    }

    /**
     * 编辑更新购物车商品
     * @param array $data
     * @param $cartId
     * @param $userId
     * @return int|mixed|string
     */
    public function updateCartGoods(array $data, $cartId, $userId)
    {
        $qb = $this->entityManager->createQueryBuilder()->update(Cart::class, 'c');

        if(isset($data['buyNum'])) $qb->set('c.buyNum', ':buyNum')->setParameter('buyNum', $data['buyNum']);
        if(isset($data['inWholesaleId'])) $qb->set('c.inWholesaleId', ':inWholesaleId')->setParameter('inWholesaleId', $data['inWholesaleId']);
        if(isset($data['goodsChecked'])) $qb->set('c.goodsChecked', ':goodsChecked')->setParameter('goodsChecked', $data['goodsChecked']);

        if($cartId > 0) $qb->where('c.cartId = :cartId')->setParameter('cartId', $cartId);
        $qb->andWhere('c.userId = :userId')->setParameter('userId', $userId);
        $qb->andWhere('c.buyNow = :buyNow')->setParameter('buyNow', 0);

        return $qb->getQuery()->execute();
    }

    /**
     * 编辑购物车，无限制编辑，很少使用
     * @param array $data
     * @param Cart $cart
     * @return Cart
     * @throws \Doctrine\ORM\Exception\ORMException
     * @throws \Doctrine\ORM\OptimisticLockException
     */
    public function editCart(array $data, Cart $cart): Cart
    {
        $cart->valuesSet($data);
        $this->entityManager->flush();

        return $cart;
    }

    /**
     * 删除指定购物车
     * @param $cartIdArray
     * @param $userId
     * @param bool $buyNowStatus
     * @return int|mixed|string
     */
    public function deleteCart($cartIdArray, $userId, bool $buyNowStatus = false)
    {
        $qb = $this->entityManager->createQueryBuilder();
        $qb->delete(Cart::class, 'c')->where($qb->expr()->in('c.cartId', $cartIdArray))
            ->andWhere('c.userId = :userId')->setParameter('userId', $userId);

        if($buyNowStatus) $qb->andWhere('c.buyNow = :buyNow')->setParameter('buyNow', 1);//删除直接购买
        else $qb->andWhere('c.buyNow = :buyNow')->setParameter('buyNow', 0);//删除购物车

        return $qb->getQuery()->execute();
    }

    /**
     * 删除购物车内的商品
     * @param $goodsId
     * @param $userId
     */
    public function shopDeleteCartGoods($goodsId, $userId)
    {
        $qb = $this->entityManager->createQueryBuilder();
        $qb->delete(Cart::class, 'c')
            ->where('c.goodsId = :goodsId')->setParameter('goodsId', $goodsId)
            ->andWhere('c.userId = :userId')->setParameter('userId', $userId);
        $qb->getQuery()->execute();
    }

    /**
     * 清空指定客户的购物车
     * @param $userId
     * @param bool $buyNowStatus
     * @return int|mixed|string
     */
    public function clearCart($userId, bool $buyNowStatus = false)
    {
        $qb = $this->entityManager->createQueryBuilder();
        $qb->delete(Cart::class, 'c')->where('c.userId = :userId')->setParameter('userId', $userId);

        if($buyNowStatus) $qb->andWhere('c.buyNow = :buyNow')->setParameter('buyNow', 1);//删除直接购买
        else $qb->andWhere('c.buyNow = :buyNow')->setParameter('buyNow', 0);//删除购物车

        return $qb->getQuery()->execute();
    }
}